<template>
  <div class="user-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <el-button type="primary" @click="handleAdd">新增用户</el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :model="searchForm" inline>
        <el-form-item label="用户名">
          <el-input v-model="searchForm.loginUserName" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="searchForm.nickName" placeholder="请输入昵称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table :data="tableData" v-loading="loading" border>
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="adminUserId" label="用户ID" width="80" align="center" />
        <el-table-column prop="loginUserName" label="用户名" min-width="120" />
        <el-table-column prop="nickName" label="昵称" min-width="120" />
        <el-table-column prop="locked" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.locked === 0 ? 'success' : 'danger'">
              {{ row.locked === 0 ? '正常' : '锁定' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="角色" min-width="150">
          <template #default="{ row }">
            <el-tag
                v-for="roleId in row.roleIds"
                :key="roleId"
                size="small"
                style="margin-right: 5px; margin-bottom: 5px;"
            >
              {{ getRoleName(roleId) }}
            </el-tag>
            <span v-if="!row.roleIds || row.roleIds.length === 0">-</span>
          </template>
        </el-table-column>
<!--        <el-table-column prop="createTime" label="创建时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatTime(row.createTime) }}
          </template>
        </el-table-column>-->
        <el-table-column label="操作" width="220" fixed="right" align="center">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="primary" @click="handleRole(row)">分配角色</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[10, 20, 50, 100]"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
            layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </el-card>

    <!-- 用户表单对话框 -->
    <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="500px"
        @close="handleDialogClose"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="用户名" prop="loginUserName">
          <el-input v-model="form.loginUserName" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.locked">
            <el-radio :label="0">正常</el-radio>
            <el-radio :label="1">锁定</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" v-model="roleDialogVisible" width="500px">
      <el-checkbox-group v-model="selectedRoleIds">
        <el-checkbox
            v-for="role in roleList"
            :key="role.roleId"
            :label="role.roleId"
            style="display: block; margin-bottom: 10px;"
        >
          {{ role.roleName }}
          <el-tag size="small" type="info" style="margin-left: 10px;">
            {{ role.roleDesc }}
          </el-tag>
        </el-checkbox>
      </el-checkbox-group>
      <template #footer>
        <el-button @click="roleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleRoleSubmit" :loading="roleSubmitLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserList, addUser, updateUser, deleteUser, updateUserRoles } from '@/utils/user'
import { getRoleList } from '@/utils/role'

const loading = ref(false)
const submitLoading = ref(false)
const roleSubmitLoading = ref(false)
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const searchForm = reactive({
  loginUserName: '',
  nickName: ''
})

const form = reactive({
  adminUserId: null,
  loginUserName: '',
  nickName: '',
  locked: 0
})

const rules = {
  loginUserName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  nickName: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '昵称长度在 2 到 20 个字符', trigger: 'blur' }
  ]
}

const dialogVisible = ref(false)
const dialogTitle = ref('')
const isAdd = ref(true)
const formRef = ref()

// 角色相关
const roleDialogVisible = ref(false)
const roleList = ref([])
const selectedRoleIds = ref([])
const currentUserId = ref(null)

// 根据角色ID获取角色名称
const getRoleName = (roleId) => {
  const role = roleList.value.find(r => r.roleId === roleId)
  return role ? role.roleName : '未知角色'
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return '-'
  return new Date(time).toLocaleString()
}

// 获取用户列表 - 修复版本
const getUserListData = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      limit: pageSize.value,
      ...searchForm
    }
    console.log('请求参数:', params)

    const res = await getUserList(params)
    console.log('用户列表返回数据:', res)

    // 直接使用返回的数据，不检查 resultCode
    if (res) {
      tableData.value = res
      total.value = res.length
      console.log('表格数据已设置:', tableData.value)
    } else {
      tableData.value = []
      total.value = 0
      console.warn('返回数据格式异常:', res)
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    // 不显示错误消息，因为可能是响应拦截器的问题
    tableData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 获取角色列表 - 修复版本
const getRoleListData = async () => {
  try {
    const res = await getRoleList()
    console.log('角色列表返回数据:', res)

    if (res) {
      roleList.value = res
    } else {
      roleList.value = []
      console.warn('角色列表返回数据格式异常:', res)
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
    roleList.value = []
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getUserListData()
}

// 重置
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增用户'
  isAdd.value = true
  Object.keys(form).forEach(key => {
    if (key === 'locked') {
      form[key] = 0
    } else {
      form[key] = ''
    }
  })
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑用户'
  isAdd.value = false
  Object.assign(form, { ...row })
  dialogVisible.value = true
}

// 分配角色
const handleRole = async (row) => {
  currentUserId.value = row.adminUserId
  selectedRoleIds.value = row.roleIds || []
  roleDialogVisible.value = true
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定删除用户 "${row.nickName}" 吗？`, '提示', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(async () => {
    try {
      const res = await deleteUser(row.adminUserId)
      if (res && res.resultCode === 200) {
        ElMessage.success('删除成功')
        getUserListData()
      } else {
        ElMessage.error(res?.message || '删除失败')
      }
    } catch (error) {
      console.error('删除用户失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 对话框关闭
const handleDialogClose = () => {
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitLoading.value = true

    let res
    if (isAdd.value) {
      res = await addUser(form)
    } else {
      res = await updateUser(form)
    }

    if (res && res.resultCode === 200) {
      ElMessage.success('操作成功')
      dialogVisible.value = false
      getUserListData()
    } else {
      ElMessage.error(res?.message || '操作失败')
    }
  } catch (error) {
    console.error('操作失败:', error)
    if (error.errors) {
      return
    }
    ElMessage.error('操作失败')
  } finally {
    submitLoading.value = false
  }
}

// 提交角色分配
const handleRoleSubmit = async () => {
  try {
    roleSubmitLoading.value = true
    const res = await updateUserRoles(currentUserId.value, selectedRoleIds.value)
    if (res && res.resultCode === 200) {
      ElMessage.success('分配角色成功')
      roleDialogVisible.value = false
      getUserListData()
    } else {
      ElMessage.error(res?.message || '分配角色失败')
    }
  } catch (error) {
    console.error('分配角色失败:', error)
    ElMessage.error('分配角色失败')
  } finally {
    roleSubmitLoading.value = false
  }
}

// 分页
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1
  getUserListData()
}

const handlePageChange = () => {
  getUserListData()
}

onMounted(() => {
  getUserListData()
  getRoleListData()
})
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table .cell) {
  white-space: nowrap;
}
</style>
